package com.fary.net;

import java.io.IOException;
import java.nio.channels.Selector;

public class NioSelectorPool {

    protected boolean enabled = true;

    protected static final boolean SHARED = Boolean.parseBoolean(System.getProperty("org.apache.tomcat.util.net.NioSelectorShared", "true"));

    protected volatile Selector SHARED_SELECTOR;

    protected NioBlockingSelector blockingSelector;

    public void open() {
        enabled = true;
        getSharedSelector();
        if (SHARED) {
            blockingSelector = new NioBlockingSelector();
            blockingSelector.open(getSharedSelector());
        }

    }

    protected Selector getSharedSelector() {
        if (SHARED && SHARED_SELECTOR == null) {
            synchronized (NioSelectorPool.class) {
                if (SHARED_SELECTOR == null) {
                    try {
                        SHARED_SELECTOR = Selector.open();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return SHARED_SELECTOR;
    }

}